package com.younio.local.service;

import com.csvreader.CsvWriter;
import com.younio.local.compnent.LanLog;
import com.younio.local.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Executor;

/**
 * @author lan  [1728209643@qq.com]
 * @create 2019-03-07 16:30
 * @desc
 */
@Slf4j
@Service
@EnableScheduling
public class VirtualService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private Symbol symbol;

    @Autowired
    private Executor executor;

    private final static String printFileDir;

    static {
        printFileDir = System.getProperty("user.dir") + File.separator + "print_csv" + File.separator;
        File file = new File(printFileDir);
        if (!file.exists()) {
            try {
                Objects.checkArguments(file.mkdirs(), "创建打印文件目录时发生错误，请手动创建");
            } catch (Exception e) {
                LanLog.info(e.getLocalizedMessage());
            }
        }
        File[] files = file.listFiles();
        if (files != null && files.length > 0) {
            log.info("正在删除文件");
            for (File f : files) {
                log.info("删除文件:{}, 是否成功:{}", f.getName(), f.delete());
            }
        }

    }

    /**
     * 第一位为机台的标志位,第2-4位为天数32进制
     */
    public synchronized List<String> get(int n) {
        String dayPreFix = getDayPreFix(System.currentTimeMillis());

        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        int current = Integer.parseInt(Objects.getOrDefault(opsForValue.get(symbol.getVirtualPrefix() + symbol.getPcSign() + dayPreFix), "0"));

        List<String> virtualNumberList = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            current++;
            virtualNumberList.add(symbol.getPcSign() + dayPreFix + current);
        }
        opsForValue
                .set(symbol.getVirtualPrefix() + symbol.getPcSign() + dayPreFix, current + "");

        return virtualNumberList;
    }

    private static final long millisOf20190101 = 1546272000000L;

    private long getDay(long millis) {
        return (millis - millisOf20190101) / 1000 / 60 / 60 / 24 + 1;
    }

    private String getDayPreFix(long millis) {
        long day = getDay(millis);
        return parse((int) day);
    }

    private String parse(int day) {
        String sDay = Integer.toString(day, 32);
        sDay = sDay.toUpperCase()
                .replaceAll("I", "W").replaceAll("L", "X").replaceAll("O", "Y").replaceAll("U", "Z");
        int length = sDay.length();
        StringBuilder prefix = new StringBuilder();
        for (int i = 0; i < 3 - length; i++) {
            prefix.append("0");
        }
        return prefix.toString() + sDay;
    }

    public List<String> get(int n, String stationName, List<Integer> lines) {
        long start = System.currentTimeMillis();
        log.info("虚拟表号");
        log.info("开始获取{}", start);
        List<String> codeList = get(n);
        long end = System.currentTimeMillis();
        log.info("成功获取:{}", end);
        log.info("耗时:{}ms", end - start);

        executor.execute(() -> createBartendPrint(stationName, lines, codeList));
        return codeList;
    }

    /**
     * 利用bartend打印，先保存csv再打印
     * csv格式
     * code,stationName,line-index
     * A123,工位1,线1-3
     *
     * @param stationName 工位名称
     * @param lines       线
     * @param codeList    码
     */
    public synchronized void createBartendPrint(String stationName, List<Integer> lines, List<String> codeList) {
        String filePath = printFileDir + codeList.get(0) + ".csv";
        CsvWriter writer = new CsvWriter(filePath, ',', Charset.forName("UTF-8"));
        int len = codeList.size();
        if (lines.size() == 2) {
            int line1 = lines.get(0);
            int line2 = lines.get(1);
            int len_2 = len / 2;
            for (int i = 0; i < len_2; i++) {
                try {
                    writer.writeRecord(new String[]{codeList.get(i), stationName, "线" + line1 + "-" + (i + 1)});
                    writer.writeRecord(new String[]{codeList.get(i + len_2), stationName, "线" + line2 + "-" + (i + 1)});
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (lines.size() == 1) {
            int line1 = lines.get(0);

            for (int i = 0; i < len; i++) {
                try {
                    writer.writeRecord(new String[]{codeList.get(i), stationName, "线" + line1 + "-" + (i + 1)});
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        writer.close();

        print(filePath);
    }

    private void print(String filePath) {
        try {
            long start = System.currentTimeMillis();
            log.info("开始打印文件:" + filePath);
            Process exec = Runtime.getRuntime().exec("bartend.exe /F=" + symbol.getVirtualPrintTemplate() + "/D=" + filePath + "/P/X");
            exec.waitFor();
            long end = System.currentTimeMillis();
            log.info("打印耗时:{}ms", end - start);
        } catch (IOException | InterruptedException e) {
            Toast.error("打印出现错误", e.getMessage());
        }
    }

}
